package com.cke.yang.preview.app.service.impl;

import com.cke.yang.preview.app.service.PrevApiService;
import com.cke.yang.preview.domain.model.PreviewLinkWrapper;
import com.cke.yang.preview.domain.strategy.ExchangeLinkStrategy;
import com.cke.yang.preview.infra.enums.ExchangeLinkModeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 预览API服务实现类
 *
 * @author yuyang
 * @date 2025-11-18 00:00:00
 */
@Slf4j
@Service
public class PrevApiServiceImpl implements PrevApiService {

    @Autowired
    private List<ExchangeLinkStrategy> processorList;

    @Override
    public PreviewLinkWrapper exchangeLink(String mode, String keyBase64) {
        ExchangeLinkModeEnum modeEnum = ExchangeLinkModeEnum.parseByCode(mode);
        if (modeEnum == null) {
            return PreviewLinkWrapper.error("入参mode错误，不符合要求，mode="+mode);
        }
        if (CollectionUtils.isEmpty(processorList)) {
            return PreviewLinkWrapper.error("处理器列表为空，无法处理");
        }
        // 对入参 keyBase64 进行base64解码，放到变量 key 里
        String key = new String(java.util.Base64.getDecoder().decode(keyBase64));

        for (ExchangeLinkStrategy strategy : processorList) {
            if (strategy.supports(modeEnum)) {
                return strategy.exchangeLink(key);
            }
        }
        return PreviewLinkWrapper.error("无匹配处理器");
    }

}
